using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GUIPanelInGame : GUIPanelWithButtons {
	
	public static GUIPanelInGame instance = null;
    public List<GameObject> soldierPrefabs = new List<GameObject>();
	public GameObject selectionArrow;
	public float portraitFlashingFactor;
	
	private List<GameObject> characters;
	
	private List<bool> isPortraitFlashing;
	private List<GameObject> redFlashObjects;

    GameObject[] m_EquippedVisual = new GameObject[4];
    Weapon[] m_equippedWeapon = new Weapon[4];
    int currentIndex = 0;
	void Awake(){
		
		instance = this;
		characters = new List<GameObject>();
		isPortraitFlashing = new List<bool>();
		redFlashObjects = new List<GameObject>();
		
		for (int i=0; i<CharacterDataManager.GetInstance().GetCharactersCount(); i++){
			GameObject go = GameObject.Instantiate((Object) soldierPrefabs[i]) as GameObject;
			go.transform.parent = this.transform;
			go.GetComponent<EventOnClicPortrait>().characterIndex = i;
			buttons.Add(go.GetComponent<GUIButton>() );
			characters.Add(go);
			isPortraitFlashing.Add(false);
			redFlashObjects.Add(go.transform.FindChild("RedFlash").gameObject );
		}

        for(int i = 0; i < 4;i++)
        {
            m_equippedWeapon[i] = null;
        }
        float width = Screen.width;
        float height = Screen.height;

		/*scaleVector = this.GetComponent<BoxCollider>().size;
		resizeFactor = (width < height) ? (float)width / MyGUI.baseWidth : (float)height / MyGUI.baseHeight;
		scaleVector.x *= resizeFactor;
		scaleVector.y *= resizeFactor;
		//scaleVector.x *= (float) width / MyGUI.baseWidth;
		//scaleVector.y *= (float) height / MyGUI.baseHeight;
        this.GetComponent<BoxCollider>().size = scaleVector;*/


		
	}
    void Start()
    {
        ShowCharacters();
        selectionArrow.transform.position = new Vector3(999, 999, 999);
		
    }
	
	void Update(){
		/*if (Input.GetKeyDown(KeyCode.Space) )
			ShowRedFlashForPortrait(0);*/
		UpdateStats();
		UpdateFlashingPortraits();
		//ShowHotSkills();
        //ShowCharacters();
		/* ESTO PONE LA FLECHITA SI NO SE CAMBIA CON EL METODO DEL CHARACTERMANAGER.
		int idx = CharacterDataManager.GetInstance().GetCurrentIndex();
		selectionArrow.transform.position = characters[idx].transform.position 
			-characters[idx].transform.localScale.x*Vector3.right;
			*/
	}
	public void LocateSelectionArrow(int charIndex){
		selectionArrow.transform.position = characters[charIndex].transform.position 
			-characters[charIndex].transform.localScale.x*Vector3.right - Vector3.forward;

        UpdateEquippedWeapon(charIndex);
	}	
	public void ShowRedFlashForPortrait(int charIndex){
		//Indico que empieza a flashear.
		isPortraitFlashing[charIndex] = true;
		//Subo el alpha de ese cuadrado rojo a 1.
	/*	Color col = redFlashObjects[charIndex].GetComponent<GUIObject>()
		.GUIMaterial.color;
		col.a = 1;
		redFlashObjects[charIndex].GetComponent<GUIObject>()
		.GUIMaterial.color = col; */
		redFlashObjects[charIndex].GetComponent<GUIObject>()
		.GUIMaterial.SetFloat("_Cutoff", 0);
	}
	public void UpdateStats(){
		int i=0;
		foreach(GameObject character in characters){
			character.GetComponentInChildren<MyGUIText>().SetText("    ");
			//Pido los atributos del character.
			CharacterData charData = CharacterDataManager.GetInstance().GetCharacterData(i);
			AttributeSet aSet;
			if (charData != null){
				aSet = charData.attributes;
			#region HPUpdate
				//Saco el porcentaje de vida actual.
				int lifePercent = (int)(aSet.GetSubAttributeActualValue(SUB_ATTRIBUTES.HIT_POINTS)
					*100/aSet.GetSubAttributeMaxValue(SUB_ATTRIBUTES.HIT_POINTS) );
				//Lo actualizo en la cariiiiiiiteee :)
				character.GetComponentInChildren<MyGUIText>().SetText(lifePercent.ToString() + "%");
				//Coloreo recopantemente según cuanta vida tiene.
				if (lifePercent < 100 && lifePercent >= 75)
					character.GetComponentInChildren<MyGUIText>().ChangeMaterial(1);
				else if (lifePercent < 75 && lifePercent >= 50)
					character.GetComponentInChildren<MyGUIText>().ChangeMaterial(2);
				else if (lifePercent < 50 && lifePercent >= 25)
					character.GetComponentInChildren<MyGUIText>().ChangeMaterial(3);
				else if (lifePercent < 25 && lifePercent > 0)
					character.GetComponentInChildren<MyGUIText>().ChangeMaterial(4);
				else
					character.GetComponentInChildren<MyGUIText>().ChangeMaterial(0);
			#endregion
			#region StaminaUpdate
				//Saco el porcentaje de stamina actual.
				int staminaPercent = (int)(aSet.GetSubAttributeActualValue(SUB_ATTRIBUTES.STAMINA)
					*100/aSet.GetSubAttributeMaxValue(SUB_ATTRIBUTES.STAMINA) );
				//Muestro barritas segun el porcentaje.
				if (staminaPercent > 90){ 
					character.GetComponent<GUIPortrait>().staminaFragments[8].SetActive(true);
				}else if (staminaPercent < 90 && staminaPercent >= 80){ 
					character.GetComponent<GUIPortrait>().staminaFragments[8].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[7].SetActive(true);
				}else if (staminaPercent < 80 && staminaPercent >= 70){
					character.GetComponent<GUIPortrait>().staminaFragments[7].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[6].SetActive(true);
				}else if (staminaPercent < 70 && staminaPercent >= 60){
					character.GetComponent<GUIPortrait>().staminaFragments[6].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[5].SetActive(true);
				}else if (staminaPercent < 60 && staminaPercent > 50){
					character.GetComponent<GUIPortrait>().staminaFragments[5].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[4].SetActive(true);
				}else if (staminaPercent < 50 && staminaPercent > 40){
					character.GetComponent<GUIPortrait>().staminaFragments[4].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[3].SetActive(true);
				}else if (staminaPercent < 40 && staminaPercent > 30){
					character.GetComponent<GUIPortrait>().staminaFragments[3].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[2].SetActive(true);
				}else if (staminaPercent < 30 && staminaPercent > 20){
					character.GetComponent<GUIPortrait>().staminaFragments[2].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[1].SetActive(true);
				}else if (staminaPercent < 20 && staminaPercent > 10){
					character.GetComponent<GUIPortrait>().staminaFragments[1].SetActive(false);
					character.GetComponent<GUIPortrait>().staminaFragments[0].SetActive(true);
				}else if (staminaPercent < 10 && staminaPercent > 0){
					character.GetComponent<GUIPortrait>().staminaFragments[0].SetActive(false);
				}
				
			#endregion
			}
			i++;
		}	
	}
	public void ShowCharacters(){
		int i=0;
		BoxCollider bc = collider as BoxCollider;
		foreach(GameObject player in characters){
			/*player.transform.position = this.transform.position 
				- Vector3.right*bc.size.x/2*this.transform.localScale.x;
			player.transform.position += 
				Vector3.up*bc.size.y/2*this.transform.localScale.y;
			
			player.transform.position += 
				player.GetComponent<GUIObject>().localSize.x/2*transform.localScale.x*Vector3.right
				+ player.GetComponent<GUIObject>().localSize.y/2*transform.localScale.y*Vector3.down
				+ player.GetComponent<GUIObject>().localSize.y*transform.localScale.y*Vector3.down*i;*/

            //magic number porque hay un problema con posicionar los portraits
            player.transform.position = this.transform.position - Vector3.right * Screen.width/40.0f + Vector3.up * Screen.height/40.0f;
            player.transform.position += + player.GetComponent<GUIObject>().localSize.y*transform.localScale.y*Vector3.down*i;
			i++;
		}
	}
	private void UpdateFlashingPortraits(){
		//Recorro todos los cuadraditos.
		for(int i=0; i<isPortraitFlashing.Count; i++){
			//Pregunto si esta flasheando
			if (isPortraitFlashing[i]){
				//Si es así, pregunto si todavia no se ve transparente.
		//		if (redFlashObjects[i].GetComponent<GUIObject>()
	//				.GUIMaterial.color.a > 0){
				float currentAlpha = redFlashObjects[i]
				.GetComponent<GUIObject>().GUIMaterial.GetFloat("_Cutoff");
				currentAlpha += portraitFlashingFactor;
					
				if (currentAlpha < 1){
					//Si es asi, sigo bajando el aplha.
					redFlashObjects[i].GetComponent<GUIObject>()
					.GUIMaterial.SetFloat("_Cutoff", currentAlpha);
				}else{//Si ya se ve transparente.
					//Indico que no está flasheando más.
					isPortraitFlashing[i] = false;	
					redFlashObjects[i].GetComponent<GUIObject>()
					.GUIMaterial.SetFloat("_Cutoff", 1);
				}
			}
				
		}
	}
    void UpdateEquippedWeapon(int index)
    {
        if (m_EquippedVisual[currentIndex] != null && m_EquippedVisual[currentIndex].renderer.enabled == true)
        {
            ShowEquipVisual(m_EquippedVisual[currentIndex], false);
        }
        currentIndex = index;
        if (m_EquippedVisual[index] != null && m_EquippedVisual[index].renderer.enabled == false)
        {
            ShowEquipVisual(m_EquippedVisual[index], true);
        }
    }
    public void OnWeaponEquip(GameObject visual, int index, Weapon weapon = null)
    {
        
        if (m_EquippedVisual[index] != null)
        {
            GameObject.Destroy(m_EquippedVisual[index]);
        }
        BoxCollider bc = collider as BoxCollider;
        GameObject equipvisual = GameObject.Instantiate((Object)visual) as GameObject;
        m_EquippedVisual[index] = equipvisual;
        equipvisual.transform.gameObject.layer = 15;
        equipvisual.transform.position = this.transform.position - Vector3.right * Screen.width/40.0f - Vector3.up * Screen.height/40.0f;
        equipvisual.transform.localScale *= 2;
        equipvisual.transform.position += Vector3.up * equipvisual.transform.localScale.y / 2.0f + Vector3.right * equipvisual.transform.localScale.x / 2.0f;

       /*if (equipvisual.transform.childCount != 0)
        {
            Transform text = equipvisual.transform.GetChild(0);
            text.gameObject.layer = 15;
        }*/
        //if(weapon != null)
        m_equippedWeapon[index] = weapon;

    }
    void ShowEquipVisual(GameObject visual, bool show)
    {
        visual.renderer.enabled = show;
    }
    public void RemoveEquipVisual(int index)
    {
        if (m_EquippedVisual[index] != null)
        {
            GameObject.Destroy(m_EquippedVisual[index]);
            m_EquippedVisual[index] = null;
            m_equippedWeapon[index] = null;
        }
    }
    Rect bulletrect = new Rect(Screen.width/5.0f,Screen.height- Screen.height/10,50,20);
    void OnGUI()
    {
        if(m_equippedWeapon[currentIndex] != null)
        {
            GUI.Box(bulletrect,m_equippedWeapon[currentIndex].GetRemainingBullets().ToString());
        }
    }
}
